package com.test.springboot.springboot3testdemo3.config;

import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.CloseableHttpClient;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.core5.util.Timeout;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/9/12-14:38
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Configuration
public class HttpConfiguration {
  /**
   * 没有实例化RestTemplate时，初始化RestTemplate
   *
   * @return
   */
  @ConditionalOnMissingBean(RestTemplate.class)
  @Bean
  public RestTemplate restTemplate() {
    RestTemplate restTemplate = new RestTemplate(getClientHttpRequestFactory());
    return restTemplate;
  }

  /**
   * 使用HttpClient作为底层客户端
   *
   * @return
   */
  private ClientHttpRequestFactory getClientHttpRequestFactory() {
    Timeout timeout = Timeout.ofSeconds(5);
    RequestConfig config =
        RequestConfig.custom()
            .setConnectTimeout(timeout)
            .setConnectionRequestTimeout(timeout)
            .build();
    CloseableHttpClient client = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
    return new HttpComponentsClientHttpRequestFactory(client);
  }
}
